package com.ics.cmsadmin.modules.sso.handler;

import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.modules.auth.bean.SysUser;
import com.ics.cmsadmin.modules.auth.service.AuthorizeService;
import com.ics.cmsadmin.modules.auth.service.UserService;
import com.ics.cmsadmin.modules.sso.LoginHandler;
import com.ics.cmsadmin.modules.sso.utils.LoginTypeEnum;
import com.ics.cmsadmin.modules.sso.utils.SsoContants;
import com.ics.cmsadmin.modules.sso.utils.SsoUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 666666 on 2018/8/25.
 */
@Component
public class CmsAdminWebLoginHandler implements LoginHandler<SysUser> {

    @Resource
    private UserService userService;
    @Resource
    private AuthorizeService authorizeService;

    @Override
    public SysUser dealWithLogin(HttpServletRequest request, HttpServletResponse response, LoginTypeEnum loginTypeEnum) {
        String username = request.getParameter(SsoContants.CMS_ADMIN_WEB_USERNAME);
        String password = request.getParameter(SsoContants.CMS_ADMIN_WEB_PASSWORD);
        if (StringUtils.isBlank(username)){
            return null;
        }
        SysUser sysUser = null;
        if (username.contains("@")){        // 判断是否为邮箱登陆
            sysUser = userService.findUserByEmailAndPassword(username, password);
        }else if (username.matches("\\d{11}")){  // 判断是否为手机登陆
            sysUser = userService.findUserByMobilephoneAndPassword(username, password);
        }
        if (sysUser == null){       // 如果不是邮箱/手机登陆,或者登陆失败,则使用用户名登陆
            sysUser = userService.findUserByUserNameAndPassword(username, password);
        }
        if (sysUser == null){
            throw new CmsException(ApiResultEnum.USER_PASSWORD_ERROR);
        }
        sysUser.setAuthCodes(authorizeService.listAuthorizesByUserId(sysUser.getUserId()));
        SsoUtils.saveLoginInfo2Redis(loginTypeEnum, sysUser);
        return sysUser;
    }
}
